import { IUser } from "@/store/user";
import { useEffect, useRef } from "react";

interface AvatarPlayerProps {
  mediaStream?: MediaStream | null;
  userInfo?: IUser | null;
  className?: string;
  type: "audio" | "video";
  loading?: boolean;
}

export function AvatarPlayer(props: AvatarPlayerProps) {
  const {
    mediaStream,
    userInfo,
    className,
    type = "video",
    loading = true,
  } = props;
  const mediaRef = useRef<HTMLVideoElement>(null);

  useEffect(() => {
    if (mediaStream && mediaRef.current) {
      mediaRef.current.srcObject = mediaStream; 
    }
  }, [mediaStream]);

  return (
    <div className={`w-[100px] h-[100px] ${className}`}>
      {mediaStream && type === "video" ? (
        <video
          className="w-full h-full object-cover rounded-none bg-black"
          ref={mediaRef} // mediaRef.current 就是 video 元素
          autoPlay
          playsInline
        ></video>
      ) : (
        <div className="relative w-full h-full">
          <img
            src={userInfo?.avatar}
            className="w-full h-full overflow-hidden p-[2px] object-cover rounded-full"
          />
          <audio ref={mediaRef} hidden playsInline autoPlay></audio>
          {/* loadin 为 false 时不显示，流不存在时不显示 loading 为 true */}
          {!mediaStream && loading && (
            <div className="absolute top-0 left-0 w-full h-full bg-black/30 rounded-full">
              <div className="flex justify-center items-center w-full space-x-1 ml-1 text-white text-[50px]">
                <span className="animate-blink delay-0">.</span>
                <span className="animate-blink delay-200">.</span>
                <span className="animate-blink delay-400">.</span>
              </div>
            </div>
          )}
        </div>
      )}
    </div>
  );
}
